﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity;
using PicStore.BLL.Interface;
using PicStore.Model;
using PicStore.Web.Lib;
using PicStore.Web.Models.Apply;

namespace PicStore.Web.Controllers
{
    public class ApplyController : BaseController
    {
        [Dependency]
        public IRequestService RequestService { get; set; }

        [Dependency]
        public ICategoryService CategoryService { get; set; }

        [Dependency]
        public IPictureService PictureService { get; set; }
        //
        // GET: /Apply/

        public ActionResult Index()
        {
            string pathFirstPart = HttpRuntime.AppDomainAppPath + ConfigurationManager.AppSettings["DownloadFolder"];
            PictureHelper.DeleteOldFolders(pathFirstPart);

            RequestService.CleanOldRequest();
            return View();
        }
        public ActionResult RequesterIndex()
        {
            return View();
        }

        public ActionResult GetRequests(string name, string orderBy, int pageIndex = 1, bool isAsc = true)
        {
            string keyTosearch = string.Empty;
            if (string.IsNullOrEmpty(name) == false)
            {
                keyTosearch = name;
            }

            int count = 0;
            int totalPages = 0;

            if (CurrentUser.Role.Name.ToLower() == RoleEnum.Viewer.ToString().ToLower() ||
                CurrentUser.Role.Name.ToLower() == RoleEnum.HighViewer.ToString().ToLower())
            {
                keyTosearch = CurrentUser.UserName;
            }
            List<RequestInfo> list = new List<RequestInfo>();
            if (CurrentUser.Role.Name.ToLower() == RoleEnum.Manager.ToString().ToLower())
            {
                list = RequestService.GetApprovedRequestList(keyTosearch, out count, out totalPages, PageSize, pageIndex);
            }
            else
            {
                list = RequestService.GetRequestList(keyTosearch, out count, out totalPages, PageSize, pageIndex);
            }

            IEnumerable<RequestModel> result = (from t in list
                                                select BuildRequestModel(t)).ToList();
            return Json(new { Data = result.ToArray(), TotalPages = totalPages }, JsonRequestBehavior.AllowGet);
        }

        private RequestModel BuildRequestModel(Model.RequestInfo request)
        {
            //var requestUser = UserService.GetUser(request.RequestUserId);
            var model = new RequestModel()
            {
                Id = request.RequestId,
                RequestUserName = request.RequestUserName,
                Phone = request.Phone + Environment.NewLine + request.Mobile,
                Project = request.Project,
                LeaderName = request.LeaderName,
                Comments = request.Comments,
                Department = request.Department,
                CreateDate = request.CreateDate.ToShortDateString(),
                ZipFileUrl = request.ZipFileUrl,
                Status = ((RequestStatus)request.Status).ToString(),
                ShowProgressIcon = false,
                ShowErrorMessage = false,
                ShowApproveButton = (request.Status == (int)RequestStatus.未处理),
                ShowDownloadButton = (request.Status == (int)RequestStatus.已处理),
                ErrorMessage = string.Empty,
            };

            if (string.IsNullOrEmpty(request.ZipFileUrl) == false)
            {
                // 下载的文件，暂存一天
                model.ShowFileUrl = (request.LastDownloadTime.Date - DateTime.Now.Date).Days <= 1;
            }
            else
            {
                model.ShowFileUrl = false;
            }

            StringBuilder builder = new StringBuilder();
            builder.AppendFormat("from {0} to {1}. ", 
                request.StartDate.ToShortDateString(), request.EndDate.ToShortDateString()).AppendLine();
            builder.Append(CategoryService.GetDescriptionOfItems(request.PlaceValue, BaseCategoryEnum.Place));
            builder.Append(CategoryService.GetDescriptionOfItems(request.SexValue, BaseCategoryEnum.Sex));
            if (string.IsNullOrEmpty(request.Comments) == false)
            {
                builder.AppendLine().Append(request.Comments);
            }

            model.Description = builder.ToString();

            return model;
        }

        

        public ActionResult ApproveAndDownload(int id)
        {
            var request = RequestService.GetRequestById(id);

            RequestService.ApproveDownloadRequest(request.RequestId, string.Empty);
            var updatedRequest = RequestService.GetRequestById(request.RequestId);
            return Json(BuildRequestModel(updatedRequest), JsonRequestBehavior.AllowGet);
        }

        public ActionResult Download(int id)
        {
            var request = RequestService.GetRequestById(id);

            List<PictureInfoForExcel> pictures = new List<PictureInfoForExcel>();
            List<string> placeArray = Convertor.ConverToStringArray(request.PlaceValue);
            List<string> sexsArray = Convertor.ConverToStringArray(request.SexValue);

            pictures = PictureService.GetPictureListForExcelWithFilters(CurrentUser.UserId,
                request.StartDate, request.EndDate, placeArray, sexsArray, null, null, null, null, null, null, null, null, null);

            return DownloadExcelWithList(request, request.NeedDownloadPicture, pictures);
        }

        private ActionResult DownloadExcelWithList(RequestInfo request, bool needDownloadPicture, List<PictureInfoForExcel> pictures)
        {
            string error;
            string zipFileUrl;
            var getZipFileSuccess = false;
            bool hasRecords = false;
            if (pictures != null)
            {
                if (pictures.Count > 0)
                {
                    hasRecords = true;
                }
            }
            if (hasRecords == false)
            {
                var model = BuildRequestModel(request);
                model.ShowErrorMessage = true;
                model.ErrorMessage = "There is no pictures to download.";
                return Json(model, JsonRequestBehavior.AllowGet);
            }
            else
            {
                getZipFileSuccess = new PictureHelper().DownloadExcelWithPictures(needDownloadPicture, pictures, out error, out zipFileUrl);
                if (getZipFileSuccess)
                {
                    RequestService.ApproveDownloadRequest(request.RequestId, zipFileUrl);
                }
                var updatedRequest = RequestService.GetRequestById(request.RequestId);
                return Json(BuildRequestModel(updatedRequest), JsonRequestBehavior.AllowGet);
            }
        }

        //
        // GET: /Apply/Delete/5

        public ActionResult Reject(int id)
        {
            var request = RequestService.GetRequestById(id);
            RequestService.RejectRequestById(id);
            return Json(BuildRequestModel(request), JsonRequestBehavior.AllowGet);
        }

        //
        // GET: /Apply/Delete/5

        public ActionResult Delete(int id)
        {
            var request = RequestService.GetRequestById(id);
            RequestService.DeleteRequestById(id);
            return Json(BuildRequestModel(request), JsonRequestBehavior.AllowGet);
        }

        public ActionResult Add()
        {
            ViewBag.Action = "Add";
            ViewBag.OnSuccess = "viewModel.onDataAdded";
            var model = new AddRequestModel();
            model.CreateTime = DateTime.Now;
            model.PlaceList = GetCategoryList(BaseCategoryEnum.Place);
            model.SexList = GetCategoryList(BaseCategoryEnum.Sex);
            model.RequestUserName = CurrentUser.UserName;
            model.Department = CurrentUser.Department;
            model.Phone = CurrentUser.Phone;
            model.Mobile = CurrentUser.Mobile;
            model.Error = string.Empty;

            return View("Add", model);
        }

        private List<SelectListItem> GetCategoryList(BaseCategoryEnum baseCategory)
        {
            var itemList = CategoryService.GetItemsByCategoryId((int)baseCategory);
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (var r in itemList)
            {
                SelectListItem item = new SelectListItem
                {
                    Text = r.ItemName,
                    Value = r.ItemValue,
                    Selected = true,
                };

                list.Add(item);
            }
            return list;
        }

        [HttpPost]
        public ActionResult Add(AddRequestModel model, FormCollection collection)
        {
            string error = string.Empty;
            if (string.IsNullOrEmpty(collection["PlaceValue"]))
            {
                model.Error = "Please select at least one place!";
                return View(model);
            }
            if (string.IsNullOrEmpty(collection["PlaceValue"]))
            {
                model.Error = "Please select at least one sex!";
                return View(model);
            }

            RequestService.SaveDownloadRequest(CurrentUser.UserId, model.StartDate, model.EndDate,
                                               model.NeedDownloadPicture, collection["PlaceValue"], collection["SexValue"], 
                                               model.Department, model.Phone, model.Mobile, model.Project,
                                               model.LeaderName, model.Comments, out error);

            if (CurrentUser.Role.Id == (int)RoleEnum.Admin)
            {
                return RedirectToAction("Index");
            }
            else
            {
                return RedirectToAction("RequesterIndex");
            }
        }
    }
}
